/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.smart.common.aspect;

import com.smart.common.annotation.WebAccess;
import com.smart.common.enums.ErrorCode;
import com.smart.common.exception.BusinessException;
import com.smart.context.SessionContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author zhanghong
 * @version SessionAspect.java, v 0.1 2023/6/22 21:32 下午 SessionAspect Exp $$
 */
@Component
@Aspect
@Order(1)
@Slf4j
public class SessionAspect {

    @Pointcut("execution(* com.smart..*Controller.*(..))")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法的签名
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        // 获取方法@WebAccess注解
        WebAccess webAccess = methodSignature.getMethod().getAnnotation(WebAccess.class);
        // 没有方法注解，获取类@WebAccess注解
        if (webAccess == null) {
            Class clazz = joinPoint.getTarget().getClass();
            webAccess = (WebAccess) clazz.getAnnotation(WebAccess.class);
        }
        // @WebAccess注解为空，直接放行
        if (webAccess == null || !webAccess.login()) {
            return joinPoint.proceed();
        }
        // 否则，从登录态获取用户信息
        Long loginAccountId = SessionContext.getLoginAccountId();
        // 用户信息为空，说明用户未登录，抛出异常
        if (loginAccountId == null) {
            throw new BusinessException(ErrorCode.LOGIN_INVALID, "登录状态已失效，请重新登录。");
        }
        // 用户信息存在，放行
        return joinPoint.proceed();
    }
}
